package cc.z8g.browser.search.suggestions

import android.text.TextUtils
import cc.z8g.browser.database.SearchSuggestion
import cc.z8g.browser.utils.FileUtils
import org.json.JSONObject
import java.io.InputStream
import java.net.URLEncoder
import java.util.Collections

/**
 * The search suggestions provider for the Baidu search engine.
 */
class BaiduSuggestionsModel : BaseSuggestionsModel() {

    // https://m.baidu.com/sugrec?pre=1&prod=wise&wd=x
    override fun createQueryUrl(word: String): String = "https://m.baidu.com/sugrec?pre=1&prod=wise&wd=" + URLEncoder.encode(word, "UTF-8")

    @Throws(Exception::class)
    override fun parseResults(bodyStream: InputStream): List<SearchSuggestion> {
        val bodyStr = FileUtils.readString(bodyStream);
        if (TextUtils.isEmpty(bodyStr)) {
            return Collections.emptyList()
        }
        val list = ArrayList<SearchSuggestion>(5)
        val ja = JSONObject(bodyStr).optJSONArray("g");
        if (ja == null || ja.length() == 0) {
            return Collections.emptyList()
        }
        for (i in 0 until ja.length()) {
            val jo = ja.getJSONObject(i)
            val query = jo.getString("q")
            val item = SearchSuggestion(suggestionStr, query)
            list.add(item);
        }
        return list
    }

}
